import React from 'react'
import { BaseListPage, IBaseListPageState, IBaseListPageProps, columnRenders, UdDateRangePicker, UdPage, UdPageHeader, UdFilter, UdTable, http } from '@/lib';
import { Badge, Select, Button, Modal, message, Tabs, BackTop, Spin } from 'antd';
import _ from 'lodash';
import apis from '@/apis/AboutQuota';
import udMainStore from '@/store/UdMain';
import { spawn } from 'child_process';
import moment from 'moment';

const { Option } = Select
const { TabPane } = Tabs;
//接口字段映射
const fieldMap = {
  //状态
  approvalStatus: "approvalStatus",
}
export enum EDealerType {
  DEALER = '经销商',
  DISTRIBUTOR = '分销商',
}
export enum EWhetherPush {
  SUCCESS = 'Y',
  ERROR = 'N',
  PENDDIDNG = 'NY',
  WAITSEND = 'WT',
}
export const whetherPushTextEnum = {
  [EWhetherPush.SUCCESS]: '推送成功',
  [EWhetherPush.ERROR]: '推送失败',
  [EWhetherPush.PENDDIDNG]: '正在推送',
  [EWhetherPush.WAITSEND]: '等待推送',
}
export default class AdjustTheRecordList extends BaseListPage<AdjustTheRecordListProps, AdjustTheRecordListState>{
  private todoTabTypes: any = [
    {
      brandName: "配额调整记录",
      brandCode: '0',
    },
    {
      brandName: "配额转移记录",
      brandCode: '1',
    }
  ]
  private statusList: any = [
    { statusCode: 'AUDITING', name: '审核中' },
    { statusCode: 'AUDITSUCC', name: '审核通过' },
    { statusCode: 'AUDITFAIL', name: '审核失败' },
  ]
  // 隐藏掉头曲二曲
  public hideArr: any = ['头曲', '二曲', '泸州老窖头曲酒类销售有限公司', '泸州老窖二曲酒类销售有限公司']
  public brandCompanies = udMainStore.brandList.filter(item => this.hideArr.indexOf(item.title) === -1)
  // public brandCompanies = udMainStore.brandList
  private columnsOne: any = [
    ['序号', 'id', (text, recode, index) => index + 1, { minWidth: '30px' }],
    ['销售组织', 'brandName', null, { minWidth: '60px' }],
    ['客户名称', 'dealerName', null, { minWidth: '140px', width: '15%' }],
    ['客户类型', 'dealerType', columnRenders.enum(EDealerType), { minWidth: '70px' }],
    ['物料分类名称', 'groupName', null, { minWidth: '140px' }],
    ['开始时间', 'quotaStartTime', (text, record) => text && moment(text).format('YYYY-MM-DD'), { minWidth: '70px' }],
    ['结束时间', 'quotaEndTime', (text, record) => text && moment(text).format('YYYY-MM-DD'), { minWidth: '70px' }],
    ['原配额数量', 'quotaNum', null, { minWidth: '70px' }],
    ['已使用数量', 'quotaUseNum', null, { minWidth: '70px' }],
    ['剩余可用数量', 'quotaCanNum', null, { minWidth: '80px' }],
    { title: '调整类型', key: 'modifyType', dataIndex: 'modifyType', minWidth: '60px', render: (text) => <span>{text == 'UP' ? '调增' : '调减'}</span> },
    ['调整数量', 'modifyNum', null, { minWidth: '60px' }],
    ['调整后剩余可用数量', 'modifyAfterNum', null, { minWidth: '110px' }],
    ['调整后配额数量', 'modifyAfterQuota', null, { minWidth: '90px' }],
    ['操作人', 'createName', null, { minWidth: '70px' }],
    ['操作时间', 'createTime', null, { minWidth: '70px' }],
    { title: "审批状态", minWidth: '70px', key: fieldMap.approvalStatus, render: (text, record, index) => this.BadgeStatus(record) },
    {
      title: "是否推送阿里订单", minWidth: '100px', dataIndex: 'sendSucc', render: (text, record, index) => {
        let color
        let statusText = whetherPushTextEnum[text]
        if (text == EWhetherPush.SUCCESS) {
          color = '#00A854'
        } else if (text == EWhetherPush.ERROR) {
          color = 'volcano'
        } else if (text == EWhetherPush.PENDDIDNG) {
          color = 'cyan'
        } else if (text == EWhetherPush.WAITSEND) {
          color = '#13c2c2'
        }
        return statusText ? <Badge color={color} text={statusText} /> : <div>-</div>
      }
    },
    {
      title: '操作',
      fixedWidth: '60px',
      dataIndex: 'opreate',
      // fixed: 'right',
      render: columnRenders.operate([
        { title: '重新推送', show: (text, model, index) => model.sendSucc == EWhetherPush.ERROR, action: (text, record) => this.handelreset(record, 'edit') }
      ])
    }
  ]
  private columnsTwo: any = [
    ['序号', 'id', (text, recode, index) => index + 1, { minWidth: '30px' }],
    ['转出客户', 'dealerName', null, { minWidth: '140px' }],
    { title: '转入客户', key: 'other', dataIndex: 'dealerNameTo', minWidth: '140px' },
    ['物料分类名称', 'groupName', null, { minWidth: '140px' }],
    ['开始时间', 'quotaStartTime', (text, record) => text && moment(text).format('YYYY-MM-DD'), { minWidth: '70px' }],
    ['结束时间', 'quotaEndTime', (text, record) => text && moment(text).format('YYYY-MM-DD'), { minWidth: '70px' }],
    ['转出客户原可用配额数量', 'quotaCanNum', null, { minWidth: '140px' }],
    ['转移配额数量', 'modifyNum', null, { minWidth: '80px' }],
    ['转出客户调整后剩余可用数量', 'modifyAfterNum', null, { minWidth: '160px' }],
    ['转入客户原可用配额数量', 'quotaCanNumTo', null, { minWidth: '140px' }],
    { title: '转入客户调整后剩余可用数量', minWidth: '160px', key: 'otherAfterNum', dataIndex: 'modifyAfterNumTo' },
    { title: "审批状态", minWidth: '70px', dataIndex: fieldMap.approvalStatus, render: (text, record, index) => this.BadgeStatus(record) },
    {
      title: "是否推送阿里订单", minWidth: '100px', dataIndex: 'sendSucc', render: (text, record, index) => {
        let color
        let statusText = whetherPushTextEnum[text]
        if (text == EWhetherPush.SUCCESS) {
          color = '#00A854'
        } else if (text == EWhetherPush.ERROR) {
          color = 'volcano'
        } else if (text == EWhetherPush.PENDDIDNG) {
          color = 'cyan'
        } else if (text == EWhetherPush.WAITSEND) {
          color = '#13c2c2'
        }
        return statusText ? <Badge color={color} text={statusText} /> : <div>-</div>
      }
    },
    {
      title: '操作',
      fixedWidth: '60px',
      dataIndex: 'opreate',
      // fixed: 'right',
      render: columnRenders.operate([
        { title: '重新推送', show: (text, model, index) => model.sendSucc == EWhetherPush.ERROR, action: (text, record) => this.handelreset(record, 'transfer') }
      ])
    }
  ]
  constructor(props) {
    super(props)
    this.state = {
      visible: false,
      title: "调整转移记录",
      rowKey: 'id',
      queryApi: (values) => {
        return http.get(apis.quotaModifyHistory, {
          params: {
            ...values,
            type: this.state.tabTyep,
          }
        })
      },
      method: 'GET',
      conditions: [
        {
          id: 'brandCode', label: '销售组织', render: () => (
            <Select placeholder="请选择销售组织">
              {this.brandCompanies.map(({ value, title }) => (<Option key={value} value={value}>{title}</Option>))}
            </Select>
          )
        },
        { id: 'dealerName', label: '客户名称' },
        { id: 'groupName', label: '物料分类名称' },
        {
          id: 'status', label: '状态', render: () => (
            <Select disabled={this.state.visible} placeholder='请选择状态'>
              {
                this.statusList.map(item => (
                  <Option value={item.statusCode}>{item.name}</Option>
                ))
              }
            </Select>
          )
        },
        {
          id: ['quotaStartTime', 'quotaEndTime'], label: '有效期', render: (record) => {
            return <UdDateRangePicker valueFormat={['YYYY-MM-DD 00:00:00', 'YYYY-MM-DD 23:59:59']} />
          }
        }

      ],
      columns: this.columnsOne,
      tableProps: {
        scroll: { x: true },
      },
      spinning: false,
      tabTyep: '0',
    }

  }

  //表格状态渲染
  private BadgeStatus = (record) => <><span style={{
    display: "inline-block",
    width: "6px",
    height: "6px",
    borderRadius: "6px",
    marginRight: "5px",
    marginBottom: "1px",
    backgroundColor: record[fieldMap.approvalStatus] == 'AUDITING' ? "#DAA520" : record[fieldMap.approvalStatus] == 'AUDITSUCC' ? "#00A854" : record[fieldMap.approvalStatus] == 'AUDITFAIL' ? "#D9001B" : ""
  }}></span><span>{
    record[fieldMap.approvalStatus] == 'AUDITING' ? "审核中" : record[fieldMap.approvalStatus] == 'AUDITSUCC' ? "审核通过" : record[fieldMap.approvalStatus] == 'AUDITFAIL' ? "审核失败" : ""
  }</span></>



  render() {
    const { conditions } = this.state
    return (
      <Spin spinning={this.state.spinning} tip='推送中，请稍等...'>
        <UdPage className="list-page">
          {
            this.state.title && <UdPageHeader title={this.state.title} subTitle={this.state.subTitle}
              onRefresh={this.query}
              affixProps={{ target: () => this.pageContainer }} />
          }
          {
            (_.isArray(conditions) && conditions.length > 0) && (
              <UdFilter
                loading={this.state.querying} items={conditions}
                getForm={(form) => { this.filterForm = form }}
                onSearch={this.handleSearch} resetAfter={this.filterReset}
              ></UdFilter>
            )
          }
          <Tabs defaultActiveKey="0" onChange={this.switchTodoTabHandle}>
            {this.todoTabTypes.map(todoTab => (
              <TabPane tab={todoTab.brandName} key={todoTab.brandCode}>
                <UdTable loading={this.state.querying} rowKey={this.state.rowKey}
                  pagination={this.state.pagination} {...this.state.tableProps}
                  columns={this.state.columns} dataSource={this.state.dataSource}
                  onChange={this.handleTableChange}
                />
              </TabPane>
            ))}
          </Tabs>

          {this.pageContainer && <BackTop target={() => this.pageContainer} visibilityHeight={100} />}
        </UdPage>
      </Spin>
    )
  }

  /* 重新推送 */
  private handelreset = (record, type) => {
    this.setState({ spinning: true })
    const { brandCode, businessKey, description } = record
    const params = { brandCode, businessKey, description, status: type }
    http.post(apis.RePushQuotaApply, params).then(res => {
      message.success('推送成功')
      this.query()
    }).finally(() => {
      this.setState({ spinning: false })
    })
  }

  private switchTodoTabHandle = (key) => {
    let columns = key == 0 ? this.columnsOne : this.columnsTwo
    this.setState({
      columns,
      tabTyep: key,
    }, () => {
      this.filterReset({} as any)
    })
  }
}

interface AdjustTheRecordListState extends IBaseListPageState {
  visible: boolean
  spinning: boolean
  tabTyep: string
}

interface AdjustTheRecordListProps extends IBaseListPageProps {

}